/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.constant.CommonConstant;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.constant.enums.IsfdBusinessDatabaseTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdDatabaseModelFieldTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdDatabaseModelShowTypeEnum;
import com.comac.ins.isfd.constant.enums.IsfdDatabaseModelSpecialFieldNameEnum;
import com.comac.ins.isfd.domain.IsfdBusinessDatabaseRef;
import com.comac.ins.isfd.domain.IsfdDatabaseModelConfig;
import com.comac.ins.isfd.domain.IsfdDatabaseModelConfigField;
import com.comac.ins.isfd.domain.IsfdDatabaseModelTree;
import com.comac.ins.isfd.domain.bo.IsfdDatabaseModelConfigFieldBo;
import com.comac.ins.isfd.domain.bo.IsfdDatabaseModelConfigQueryBo;
import com.comac.ins.isfd.domain.bo.IsfdDatabaseModelConfigSaveBo;
import com.comac.ins.isfd.domain.bo.IsfdDatabaseModelConfigUpgradeBo;
import com.comac.ins.isfd.domain.vo.*;
import com.comac.ins.isfd.mapper.*;
import com.comac.ins.isfd.service.IIsfdDatabaseModelConfigService;
import com.comac.ins.isfd.service.IIsfdDatabaseMongoService;
import com.comac.ins.system.domain.bo.SysDictDataBo;
import com.comac.ins.system.domain.vo.SysDictDataVo;
import com.comac.ins.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 数据库建模配置Service业务层处理
 *
 * @author lj
 * @date 2025-01-16
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class IsfdDatabaseModelConfigServiceImpl implements IIsfdDatabaseModelConfigService {

    @Autowired
    private final IsfdDatabaseModelConfigMapper baseMapper;

    @Autowired
    private IsfdDatabaseModelConfigFieldMapper fieldMapper;

    @Autowired
    private IIsfdDatabaseMongoService mongoService;

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private IsfdDatabaseModelTreeMapper treeMapper;

    @Autowired
    private IsfdBusinessDatabaseRefMapper isfdBusinessDatabaseRefMapper;

    @Autowired
    private IsfdBusinessScenariosMapper isfdBusinessScenariosMapper;

    @Autowired
    private IsfdDatabaseTypeManagementMapper isfdDatabaseTypeManagementMapper;

    @Override
    public Boolean refresh() {
        List<IsfdDatabaseModelConfigVo> isfdDatabaseModelConfigVos = baseMapper.selectVoList();
        List<String> tableNames = isfdDatabaseModelConfigVos.stream()
            .map(IsfdDatabaseModelConfigVo::getTableName)
            .toList();
        List<String> collectionNames = mongoService.findAllCollectionName();

         // 找出存在于tableNames但不存在于collectionNames中的表名（需要创建的集合）
        List<String> collectionsToCreate = tableNames.stream()
            .filter(tableName -> !collectionNames.contains(tableName))
            .toList();

        // 为每个需要创建的集合调用创建方法
        collectionsToCreate.forEach(mongoService::createCollection);
        return Boolean.TRUE;
    }

    @Override
    public List<IsfdDatabaseModelConfigVo> allList() {
        return baseMapper.selectVoList();
    }

    @Override
    public TableDataInfo<IsfdDatabaseModelConfigVo> collectCardList(Integer pageNum, Integer pageSize, String modelName) {
        PageQuery pageQuery = new PageQuery();
        if (pageNum != null) {
            pageQuery.setPageNum(pageNum);
        }
        if (pageSize != null) {
            pageQuery.setPageSize(pageSize);
        }
        QueryWrapper<IsfdDatabaseModelConfig> lqw = Wrappers.query();
        lqw.isNull("c.parent_config_id")
            .gt("t.id", 0)
            .like(StringUtils.isNotBlank(modelName), "c.model_name", modelName)
            .orderByDesc("c.create_time");
        Page<IsfdDatabaseModelConfigVo> result = baseMapper.collectCardList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public IsfdDatabaseModelConfigVo collectCardDetail(Long modelId) {
        IsfdDatabaseModelConfigVo modelConfigVo = baseMapper.selectVoById(modelId);
        if (modelConfigVo == null) {
            throw new BaseException("未查到模型数据！");
        }
        List<IsfdDatabaseModelConfigVo> allChildren = this.getAllChildrenByParentConfigId(modelId);
        modelConfigVo.setChildren(allChildren);
        // 改版后的关联关系只有一条，说明一个模型只能被 一个业务场景、一个要素库类型、一个业务系统使用
        List<IsfdBusinessDatabaseRefWithNameVo> allDataWithNames = isfdBusinessDatabaseRefMapper.getAllDataWithNames(null, null, Collections.singletonList(modelId), null);
        IsfdBusinessDatabaseRefWithNameVo isfdBusinessDatabaseRefWithNameVo = allDataWithNames.get(0);

        // 要素数据库类型
        Long databaseTypeId = isfdBusinessDatabaseRefWithNameVo.getDatabaseTypeId();
        if (databaseTypeId != null) {
            IsfdDatabaseTypeManagementVo isfdDatabaseTypeManagementVo = isfdDatabaseTypeManagementMapper.selectVoById(databaseTypeId);
            if (isfdDatabaseTypeManagementVo != null) {
                modelConfigVo.setIsfdDatabaseTypeManagementVo(isfdDatabaseTypeManagementVo);
            }
        }

        Long sceneId = isfdBusinessDatabaseRefWithNameVo.getSceneId();
        // 业务场景
        if (sceneId != null) {
            IsfdBusinessScenariosVo sceneVo = isfdBusinessScenariosMapper.selectVoById(sceneId);
            if (sceneVo != null) {
                modelConfigVo.setSceneVo(sceneVo);
            }
        }

        // 业务系统
        Long systemId = isfdBusinessDatabaseRefWithNameVo.getSystemId();
        if (systemId != null) {
            IsfdBusinessScenariosVo systemVo = isfdBusinessScenariosMapper.selectVoById(systemId);
            if (systemVo != null) {
                modelConfigVo.setSystemVo(systemVo);
            }
        }
        return modelConfigVo;
    }

    /**
     * 分页查询数据库建模配置列表
     *
     * @return 数据库建模配置分页列表
     */
    @Override
    public TableDataInfo<IsfdDatabaseModelConfigVo> queryPageList(IsfdDatabaseModelConfigQueryBo queryBo) {
        // 获取所有子节点
        Long nodeId = queryBo.getNodeId();
        if (nodeId == null) {
            List<IsfdDatabaseModelTree> treeList = treeMapper.selectList(
                new LambdaQueryWrapper<IsfdDatabaseModelTree>()
                    .isNull(IsfdDatabaseModelTree::getParentId)
            );
            if (CollectionUtils.isEmpty(treeList)) {
                throw new BaseException("找不到根节点，请检查配置！");
            }
            nodeId = treeList.get(0).getId();
        }
        List<Long> subNodeIds = getSubNodeIds(nodeId);
        Long modelId = queryBo.getModelId();
        List<Long> allVersionIds = new ArrayList<>();
        Map<String, Long> versionIdMap = modelId != null ? getVersionIdMap(modelId) : null;
        if (modelId != null) {
            allVersionIds.addAll(versionIdMap.values());
        }
        PageQuery pageQuery = queryBo.getPageQuery();
        LambdaQueryWrapper<IsfdDatabaseModelConfig> lqw = new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
            .orderByAsc(IsfdDatabaseModelConfig::getModelName)
            .orderByAsc(IsfdDatabaseModelConfig::getCreateTime)
            .in(IsfdDatabaseModelConfig::getNodeId, subNodeIds)
            .eq(StringUtils.isNotBlank(queryBo.getModelType()), IsfdDatabaseModelConfig::getModelType, queryBo.getModelType())
            .like(StringUtils.isNotBlank(queryBo.getModelName()), IsfdDatabaseModelConfig::getModelName, queryBo.getModelName());
        if (modelId == null && StringUtils.isBlank(queryBo.getModelName())) {
            lqw.isNull(IsfdDatabaseModelConfig::getParentConfigId);
        } else if (!CollectionUtils.isEmpty(allVersionIds)) {
            lqw.in(IsfdDatabaseModelConfig::getId, allVersionIds);
        }
        long total = baseMapper.selectCount(lqw);
        // 获取所有版本的根模型
        List<IsfdDatabaseModelConfig> rootModels = baseMapper.selectList(pageQuery.build(), lqw);
        // 获取所有模型
        List<Long> allModelIds = rootModels.stream().map(root -> getSubModelIds(root.getId())).flatMap(List::stream).toList();
        if (CollectionUtils.isEmpty(allModelIds)) {
            return TableDataInfo.build();
        }
        List<IsfdDatabaseModelConfig> result = baseMapper.selectBatchIds(allModelIds);
        Map<Long, IsfdDatabaseModelConfigVo> resultVo = new HashMap<>();
        // 获取最新版本
        Map<Long, List<IsfdDatabaseModelConfig>> resultMap = result.stream()
            .collect(Collectors.groupingBy(
                config -> config.getOriginalVersionId() == null ? config.getId() : config.getOriginalVersionId()
            ));
        for (Map.Entry<Long, List<IsfdDatabaseModelConfig>> entry : resultMap.entrySet()) {
            List<IsfdDatabaseModelConfig> configList = entry.getValue();
            List<IsfdDatabaseModelConfigVo> configVoList = sortLatestConfigSimple(configList);
            for (IsfdDatabaseModelConfigVo vo : configVoList) {
                vo.setVersionIdMap(versionIdMap == null ? getVersionIdMap(vo.getId()) : versionIdMap);
                resultVo.put(vo.getId(), vo);
            }
        }
        // 拼接层级
        return TableDataInfo.build(createConfigTree(resultVo), total);
    }

    private List<IsfdDatabaseModelConfigVo> createConfigTree(Map<Long, IsfdDatabaseModelConfigVo> resultMap) {
        if (CollectionUtils.isEmpty(resultMap)) {
            return Collections.emptyList();
        }
        Map<Long, List<IsfdDatabaseModelConfigVo>> configMap = new HashMap<>();
        List<IsfdDatabaseModelConfigVo> result = new ArrayList<>();
        for (IsfdDatabaseModelConfigVo config : resultMap.values()) {
            if (config.getParentConfigId() != null) {
                if (!resultMap.containsKey(config.getParentConfigId())) {
                    result.add(config);
                    continue;
                }
                configMap.putIfAbsent(config.getParentConfigId(), new ArrayList<>());
                configMap.get(config.getParentConfigId()).add(config);
            } else {
                result.add(config);
            }
        }
        if (CollectionUtils.isEmpty(result)) {
            throw new BaseException("列表为空！");
        }

        // **对顶层节点按创建时间排序**
        if (CollectionUtils.isEmpty(configMap)) {
            result.sort(Comparator.comparing(IsfdDatabaseModelConfigVo::getModelName, Comparator.nullsLast(String::compareTo))
                .thenComparing(IsfdDatabaseModelConfigVo::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())));
            return result;
        }
        result.forEach(config -> {
            config.setChildren(new ArrayList<>());
            getChildren(config, configMap);
        });
        result.sort(Comparator.comparing(IsfdDatabaseModelConfigVo::getModelName, Comparator.nullsLast(String::compareTo))
            .thenComparing(IsfdDatabaseModelConfigVo::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())));

        return result;
    }

    private IsfdDatabaseModelConfigVo getChildren(IsfdDatabaseModelConfigVo config, Map<Long, List<IsfdDatabaseModelConfigVo>> configMap) {
        List<IsfdDatabaseModelConfigVo> children = configMap.get(config.getId());
        if (CollectionUtils.isEmpty(children)) {
            return config;
        }
        if (config.getChildren() == null) {
            config.setChildren(new ArrayList<>());
        }
        for (IsfdDatabaseModelConfigVo child : children) {
            config.getChildren().add(getChildren(child, configMap));
        }
        return config;
    }


    /**
     * 获取所有子模型id
     */
    private List<Long> getSubModelIds(Long modelId) {
        IsfdDatabaseModelConfig model = baseMapper.selectById(modelId);
        if (model == null) {
            return null;
        }
        // 一次性查询所有节点
        List<IsfdDatabaseModelConfig> allSubModels = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .isNotNull(IsfdDatabaseModelConfig::getParentConfigId)
        );
        Map<Long, List<IsfdDatabaseModelConfig>> subModelMap = allSubModels.stream()
            .collect(Collectors.groupingBy(IsfdDatabaseModelConfig::getParentConfigId));
        return getSubModelIds(model, subModelMap);
    }
    private List<Long> getSubModelIds(IsfdDatabaseModelConfig model, Map<Long, List<IsfdDatabaseModelConfig>> subModelMap) {
        // 获取当前节点的子节点列表
        List<IsfdDatabaseModelConfig> children = subModelMap.get(model.getId());
        if (CollectionUtil.isEmpty(children)) {
            // 如果没有子节点，则返回一个只包含当前节点的列表
            return List.of(model.getId());
        }
        // 初始化一个列表来保存所有的子节点（包括递归获取的子孙节点）
        List<Long> allNodeId = new ArrayList<>();
        allNodeId.add(model.getId()); // 添加当前节点
        // 遍历子节点并递归获取子孙节点
        for (IsfdDatabaseModelConfig child : children) {
            allNodeId.addAll(getSubModelIds(child, subModelMap));
        }
        return allNodeId;
    }
    /**
     * 获取所有的子树
     */
    public List<Long> getSubNodeIds(Long nodeId) {
        IsfdDatabaseModelTree node = treeMapper.selectById(nodeId);
        if (node == null) {
            throw new BaseException("无法找到该节点！id: " + nodeId);
        }
        // 一次性查询所有节点
        List<IsfdDatabaseModelTree> allNodes = treeMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelTree>()
                .isNotNull(IsfdDatabaseModelTree::getParentId)
        );
        // 构建父子节点映射
        Map<Long, List<IsfdDatabaseModelTree>> nodeMap = allNodes.stream()
            .collect(Collectors.groupingBy(IsfdDatabaseModelTree::getParentId));
        return getSubNodeIds(node, nodeMap);
    }

    private List<Long> getSubNodeIds(IsfdDatabaseModelTree node, Map<Long, List<IsfdDatabaseModelTree>> nodeMap) {
        // 获取当前节点的子节点列表
        List<IsfdDatabaseModelTree> children = nodeMap.get(node.getId());
        if (CollectionUtil.isEmpty(children)) {
            // 如果没有子节点，则返回一个只包含当前节点的列表
            return List.of(node.getId());
        }
        // 初始化一个列表来保存所有的子节点（包括递归获取的子孙节点）
        List<Long> allNodeId = new ArrayList<>();
        allNodeId.add(node.getId()); // 添加当前节点
        // 遍历子节点并递归获取子孙节点
        for (IsfdDatabaseModelTree child : children) {
            allNodeId.addAll(getSubNodeIds(child, nodeMap));
        }
        return allNodeId;
    }

    /**
     * 查询数据库建模配置
     *
     * @param id 主键
     * @return 数据库建模配置
     */
    @Override
    public IsfdDatabaseModelConfigShowVo queryById(Long id) {
        IsfdDatabaseModelConfig config = baseMapper.selectById(id);
        if (config == null) {
            throw new RuntimeException("未查询到模型！");
        }
        // 实时查询父模型信息
        if (config.getParentConfigId() != null) {
            IsfdDatabaseModelConfig parentConfig = baseMapper.selectById(config.getParentConfigId());
            if (parentConfig == null) {
                throw new RuntimeException("未查询到关联模型！");
            }
            IsfdDatabaseModelConfigField parentField = fieldMapper.selectById(config.getParentConfigFieldId());
            if (parentField == null) {
                throw new RuntimeException("未查询到关联模型字段！");
            }
            config.setParentConfigName(parentConfig.getModelName());
            config.setParentConfigFieldName(parentField.getFieldName());
            baseMapper.updateById(config);
        }

        Long dataAmount = mongoService.count(config.getTableName());
        if (dataAmount > 0) {
            config.setIsPublished(1);
            baseMapper.updateById(config);
        }
        List<IsfdDatabaseModelConfigField> fieldList = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, id)
                .isNull(IsfdDatabaseModelConfigField::getParentFieldId));
        IsfdDatabaseModelConfigShowVo showVo = MapstructUtils.convert(config, IsfdDatabaseModelConfigShowVo.class);
        if (showVo == null || fieldList == null) {
            // 模型为空返回空对象
            return new IsfdDatabaseModelConfigShowVo();
        }
        List<IsfdDatabaseModelConfigFieldVo> fieldVoList = fieldList.stream()
            .map(this::createFieldTree).toList();
        showVo.setFieldList(fieldVoList);
        Map<String, Long> versionIdMap = getVersionIdMap(id);
        showVo.setVersionIdMap(versionIdMap);

        //封装返回 库类型、业务场景、业务系统
        IsfdDatabaseModelConfig topParent = this.queryByIdReturnTopParent(id);
        if (topParent == null) {
            throw new RuntimeException("未查询到模型！");
        }
        List<IsfdBusinessDatabaseRefWithNameVo> allDataWithNames = isfdBusinessDatabaseRefMapper.getAllDataWithNames(null, null, Collections.singletonList(topParent.getId()), null);
        IsfdBusinessDatabaseRefWithNameVo isfdBusinessDatabaseRefWithNameVo = allDataWithNames.get(0);
        Long sceneId = isfdBusinessDatabaseRefWithNameVo.getSceneId();
        // 要素数据库类型
        Long databaseTypeId = isfdBusinessDatabaseRefWithNameVo.getDatabaseTypeId();
        if (databaseTypeId != null) {
            IsfdDatabaseTypeManagementVo isfdDatabaseTypeManagementVo = isfdDatabaseTypeManagementMapper.selectVoById(databaseTypeId);
            if (isfdDatabaseTypeManagementVo != null) {
                Long level = isfdDatabaseTypeManagementVo.getLevel();
                showVo.setDatabaseTypeId(isfdDatabaseTypeManagementVo.getId());
                showVo.setDatabaseTypeName(isfdDatabaseTypeManagementVo.getDatabaseName());
                if (level == 2) {
                    Long parentId = isfdDatabaseTypeManagementVo.getParentId();
                    IsfdDatabaseTypeManagementVo parentDatabaseTypeVo = isfdDatabaseTypeManagementMapper.selectVoById(parentId);
                    String databaseNameLevel1 = parentDatabaseTypeVo.getDatabaseName();
                    showVo.setDatabaseTypeName(databaseNameLevel1 + "-" + isfdDatabaseTypeManagementVo.getDatabaseName());
                }
            }
        }

        // 业务场景
        if (sceneId != null) {
            IsfdBusinessScenariosVo sceneVo = isfdBusinessScenariosMapper.selectVoById(sceneId);
            if (sceneVo != null) {
                showVo.setSceneId(sceneVo.getId());
                showVo.setSceneName(sceneVo.getName());
            }
        }

        // 业务系统
        Long systemId = isfdBusinessDatabaseRefWithNameVo.getSystemId();
        if (systemId != null) {
            IsfdBusinessScenariosVo systemVo = isfdBusinessScenariosMapper.selectVoById(systemId);
            if (systemVo != null) {
                showVo.setSystemId(systemVo.getId());
                showVo.setSystemName(systemVo.getName());
            }
        }
        return showVo;
    }

    private IsfdDatabaseModelConfigFieldVo createFieldTree(IsfdDatabaseModelConfigField field) {
        IsfdDatabaseModelConfigFieldVo fieldVo = MapstructUtils.convert(field, IsfdDatabaseModelConfigFieldVo.class);
        if (field.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.MODEL.getValue()) && field.getIsRelated().equals(1)) {
            try {
                IsfdDatabaseModelConfigVo relatedModel = baseMapper.selectVoOne(new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                    .eq(IsfdDatabaseModelConfig::getParentConfigId, fieldVo.getModelId())
                    .eq(IsfdDatabaseModelConfig::getParentConfigFieldId, fieldVo.getId()));
                if (relatedModel == null) {
                    log.error("未找到子模型模型！");
                    throw new BaseException("未找到子模型模型！");
                }
                fieldVo.setRelatedModelId(relatedModel.getId());
            } catch (BaseException e) {
                throw new BaseException(e.getMessage());
            }
        }
        if (!field.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.OBJECT.getValue()) &&
            !field.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.LIST.getValue())) {
            return fieldVo;
        }
        List<IsfdDatabaseModelConfigField> subFields = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getParentFieldId, field.getId())
        );
        List<IsfdDatabaseModelConfigFieldVo> fieldVoList = new ArrayList<>();
        for (IsfdDatabaseModelConfigField subField : subFields) {
            IsfdDatabaseModelConfigFieldVo subFieldVo = createFieldTree(subField);
            fieldVoList.add(subFieldVo);
        }
        fieldVo.setFieldList(fieldVoList);
        return fieldVo;
    }

    private List<IsfdDatabaseModelConfigFieldBo> getFieldBoList(Long modelId) {
        List<IsfdDatabaseModelConfigField> fieldList = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, modelId)
                .isNull(IsfdDatabaseModelConfigField::getParentFieldId));
        if (CollectionUtil.isEmpty(fieldList)) {
            throw new BaseException("字段列表为空！模型id：" + modelId);
        }
        List<IsfdDatabaseModelConfigFieldBo> fieldBoList = new ArrayList<>();
        for (IsfdDatabaseModelConfigField field : fieldList) {
            // 如果当前field有被其他模型关联，则从list中去掉，需要单独处理关联
            IsfdDatabaseModelConfig connectedConfig = baseMapper.selectOne(
                new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                    .eq(IsfdDatabaseModelConfig::getParentConfigFieldId, field.getId())
            );
            if (connectedConfig != null) {
                continue;
            }
            // 其他正常情况
            field.setIsRelated(0);
            fieldBoList.add(createFieldTreeBo(field));
        }
        return fieldBoList;
    }

    private IsfdDatabaseModelConfigFieldBo createFieldTreeBo(IsfdDatabaseModelConfigField field) {
        // 将 Field 转换为 FieldBo
        IsfdDatabaseModelConfigFieldBo fieldBo = MapstructUtils.convert(field, IsfdDatabaseModelConfigFieldBo.class);
        fieldBo.setId(null);
        fieldBo.setModelId(null);
        // 如果当前字段不是 objectFieldType，直接返回
        if (!field.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.OBJECT.getValue())) {
            return fieldBo;
        }
        // 查询子字段列表
        List<IsfdDatabaseModelConfigField> subFields = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getParentFieldId, field.getId())
        );
        // 如果有子字段，则递归创建子字段树
        if (!subFields.isEmpty()) {
            List<IsfdDatabaseModelConfigFieldBo> subFieldBos = subFields.stream()
                .map(this::createFieldTreeBo) // 递归创建子字段树
                .collect(Collectors.toList());
            fieldBo.setFieldList(subFieldBos);  // 设置子字段列表
        }
        return fieldBo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean upgradeConfig(IsfdDatabaseModelConfigUpgradeBo upgradeBo) {
        // 校验参数
        IsfdDatabaseModelConfig currentConfig = baseMapper.selectById(upgradeBo.getPreviousVersionId());
        if (currentConfig == null) {
            throw new BaseException("未找到上一个版本，id：" + upgradeBo.getPreviousVersionId());
        }
        // 获取根
        IsfdDatabaseModelConfig rootConfig = getRootConfig(currentConfig);
        IsfdDatabaseModelConfigSaveBo rootSaveBo = MapstructUtils.convert(rootConfig, IsfdDatabaseModelConfigSaveBo.class);
        rootSaveBo.setId(null);
        rootSaveBo.setVersionNumber(upgradeBo.getVersionNumber());
        rootSaveBo.setPreviousVersionId(rootConfig.getId());
        rootSaveBo.setOriginalVersionId(rootConfig.getOriginalVersionId());
        // 改版后的关联关系只有一条，说明一个模型只能被 一个业务场景、一个要素库类型、一个业务系统使用
        List<IsfdBusinessDatabaseRefWithNameVo> allDataWithNames = isfdBusinessDatabaseRefMapper.getAllDataWithNames(null, null, Collections.singletonList(rootConfig.getId()), null);
        IsfdBusinessDatabaseRefWithNameVo isfdBusinessDatabaseRefWithNameVo = allDataWithNames.get(0);
        rootSaveBo.setDatabaseTypeId(isfdBusinessDatabaseRefWithNameVo.getDatabaseTypeId());
        rootSaveBo.setSceneId(isfdBusinessDatabaseRefWithNameVo.getSceneId());
        rootSaveBo.setSystemId(isfdBusinessDatabaseRefWithNameVo.getSystemId());
        // 建立关联模型树
        upgradeModelVersionInOrder(rootSaveBo, upgradeBo);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void upgradeModelVersionInOrder(IsfdDatabaseModelConfigSaveBo saveBo, IsfdDatabaseModelConfigUpgradeBo upgradeBo) {
        // 完成新增操作
        saveBo.setFieldList(getFieldBoList(saveBo.getPreviousVersionId()));
        saveConfig(saveBo, Boolean.TRUE);
        // 子模型
        List<IsfdDatabaseModelConfig> childConfigs = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getParentConfigId, saveBo.getPreviousVersionId())
        );
        if (CollectionUtil.isEmpty(childConfigs)) {
            return;
        }
        for (IsfdDatabaseModelConfig childConfig : childConfigs) {
            if (childConfig.getOriginalVersionId() == null) {
                childConfig.setOriginalVersionId(childConfig.getId());
            }
            IsfdDatabaseModelConfigSaveBo childSaveBo = MapstructUtils.convert(childConfig, IsfdDatabaseModelConfigSaveBo.class);
            childSaveBo.setId(null);
            childSaveBo.setVersionNumber(upgradeBo.getVersionNumber());
            childSaveBo.setPreviousVersionId(childConfig.getId());
            // 新增关联字段
            IsfdDatabaseModelConfigField relatedField = fieldMapper.selectById(childConfig.getParentConfigFieldId());
            IsfdDatabaseModelConfigField overrideField = fieldMapper.selectOne(
                new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                    .eq(IsfdDatabaseModelConfigField::getModelId, saveBo.getId())
                    .eq(IsfdDatabaseModelConfigField::getFieldName, relatedField.getFieldName())
            );
            if (overrideField != null) {
                fieldMapper.deleteById(overrideField.getId());
            }
            relatedField.setId(null);
            assert saveBo.getId() != null;
            relatedField.setModelId(saveBo.getId());
            relatedField.setIsRelated(1);
            relatedField.setFieldType(IsfdDatabaseModelFieldTypeEnum.MODEL.getValue());
            relatedField.setParentFieldId(null);
            fieldMapper.insert(relatedField);
            assert relatedField.getId() != null;
            childSaveBo.setParentConfigId(saveBo.getId());
            childSaveBo.setParentConfigFieldId(relatedField.getId());
            upgradeModelVersionInOrder(childSaveBo, upgradeBo);
        }
    }

    private IsfdDatabaseModelConfig getRootConfig(IsfdDatabaseModelConfig currentConfig) {
        if (currentConfig.getParentConfigId() == null) {
            return currentConfig;
        }
        IsfdDatabaseModelConfig parentConfig = baseMapper.selectById(currentConfig.getParentConfigId());
        if (parentConfig == null) {
            throw new BaseException("未找到父模型，id: " + currentConfig.getParentConfigId());
        }
        return getRootConfig(parentConfig);
    }

    @Override
    public Map<String, Long> getVersionIdMap(Long id) {

        IsfdDatabaseModelConfig currentConfig = baseMapper.selectById(id);
        if (currentConfig == null) {
            throw new BaseException("未找到模型，id：");
        }
        Long originalVersionId = currentConfig.getOriginalVersionId();
        List<IsfdDatabaseModelConfig> relatedConfigs = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getOriginalVersionId, originalVersionId)
        );
        return relatedConfigs.stream()
            .sorted(Comparator.comparing(IsfdDatabaseModelConfig::getCreateTime).reversed()) // 按时间降序
            .collect(Collectors.toMap(
                IsfdDatabaseModelConfig::getVersionNumber, // key: 版本号
                IsfdDatabaseModelConfig::getId,           // value: ID
                (oldValue, newValue) -> oldValue,         // 处理 key 冲突（保留旧值）
                LinkedHashMap::new                         // 保持插入顺序
            ));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveConfig(IsfdDatabaseModelConfigSaveBo saveBo, Boolean isUpdatingConfig) {
        // 验证是新增/升版还是修改
        boolean isUpdate = isUpdatingConfig(saveBo);
        // 校验模型是否存在
        validateModelExistence(saveBo);
        // 验证父模型是否存在
        validateParentModelExistence(saveBo);
        // 新增/修改模型
        IsfdDatabaseModelConfig model = MapstructUtils.convert(saveBo, IsfdDatabaseModelConfig.class);
        baseMapper.insertOrUpdate(model);
        assert model != null;
        Long modelId = model.getId();
        saveBo.setId(modelId);
        // 新增的时候维护 根版本号 字段
        saveOriginalVersionId(model, modelId, isUpdate, isUpdatingConfig);
        // 保存字段配置
        saveFieldConfig(saveBo.getFieldList(), modelId);
        // MongoDB操作
        handleMongoOperations(saveBo, isUpdate);
        // 维护关联关系
        saveBusinessDatabaseRef(saveBo, model);
        return Boolean.TRUE;
    }

    /**
     * 保存关联关系
     * 只保存parentConfigId 为null的模型 即父模型
     */
    private void saveBusinessDatabaseRef(IsfdDatabaseModelConfigSaveBo saveBo, IsfdDatabaseModelConfig model) {
        if (model.getParentConfigId() == null) {
            IsfdBusinessDatabaseRef one = isfdBusinessDatabaseRefMapper.selectOne(new LambdaQueryWrapper<IsfdBusinessDatabaseRef>()
                .eq(IsfdBusinessDatabaseRef::getSceneId, saveBo.getSceneId())
                .eq(IsfdBusinessDatabaseRef::getDatabaseTypeId, saveBo.getDatabaseTypeId())
                .eq(saveBo.getSystemId() != null, IsfdBusinessDatabaseRef::getSystemId, saveBo.getSystemId())
                .eq(IsfdBusinessDatabaseRef::getParentModelId, model.getId()));
            if (one != null) {
                return;
            }
            IsfdBusinessDatabaseRef po = new IsfdBusinessDatabaseRef();
            po.setDatabaseTypeId(saveBo.getDatabaseTypeId());
            po.setSceneId(saveBo.getSceneId());
            if (saveBo.getSystemId() != null) {
                po.setSystemId(saveBo.getSystemId());
            }
            po.setModelType(model.getModelType());
            po.setParentModelId(model.getId());
            po.setOriginalVersionId(model.getOriginalVersionId());
            isfdBusinessDatabaseRefMapper.insert(po);
        }
    }

    private void validateModelExistence(IsfdDatabaseModelConfigSaveBo saveBo) {
        Long nodeId = saveBo.getNodeId();
        String modelName = saveBo.getModelName();
        String versionNumber = saveBo.getVersionNumber();
        IsfdDatabaseModelConfig existConfig = null;
        try {
            existConfig = baseMapper.selectOne(
                new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                    .eq(IsfdDatabaseModelConfig::getNodeId, nodeId)
                    .eq(IsfdDatabaseModelConfig::getModelName, modelName)
                    .eq(IsfdDatabaseModelConfig::getVersionNumber, versionNumber)
            );
        } catch (Exception e) {
            throw new BaseException("该节点下存在重复版本模型，请联系管理员解决，名称：" + modelName + ", 版本：" + versionNumber);
        }
        if (existConfig != null && (saveBo.getId() == null || !existConfig.getId().equals(saveBo.getId()))) {
            throw new BaseException("已存在该模型！");
        }
        IsfdDatabaseModelTree node = treeMapper.selectById(nodeId);
        if (node == null) {
            throw new BaseException("节点不存在！node id: " + nodeId);
        }
        saveBo.setNodeName(node.getName());
    }

    private void validateParentModelExistence(IsfdDatabaseModelConfigSaveBo saveBo) {
        Long parentModelId = saveBo.getParentConfigId();
        if (parentModelId == null) {
            saveBo.setShowType(IsfdDatabaseModelShowTypeEnum.TREE.getValue());
            return;
        }
        IsfdDatabaseModelShowTypeEnum showType = IsfdDatabaseModelShowTypeEnum.forValue(saveBo.getShowType());
        if (showType == null) {
            throw new BaseException("展示方式设置有误！");
        }
        if (saveBo.getId() != null && parentModelId.equals(saveBo.getId())) {
            throw new BaseException("不能关联本身！");
        }
        IsfdDatabaseModelConfig parentModel = baseMapper.selectById(parentModelId);
        if (parentModel == null) {
            throw new BaseException("父模型不存在！");
        }
        if (Objects.equals(parentModel.getModelName(), saveBo.getModelName())) {
            throw new BaseException("模型名称不能与父模型一致！");
        }
        saveBo.setParentConfigName(parentModel.getModelName());
        Long parentFieldId = saveBo.getParentConfigFieldId();
        IsfdDatabaseModelConfigField parentField = fieldMapper.selectById(parentFieldId);
        if (parentField == null) {
            throw new BaseException("关联父模型字段不存在！");
        }
        IsfdDatabaseModelConfig connectedConfig = baseMapper.selectOne(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getParentConfigFieldId, parentFieldId)
        );
        if (connectedConfig != null && !connectedConfig.getId().equals(saveBo.getId())) {
            throw new BaseException("当前字段已关联！字段名称：" + parentField.getFieldName());
        }
        // 去除原本的关联
        if (saveBo.getId() != null) {
            IsfdDatabaseModelConfig config = baseMapper.selectById(saveBo.getId());
            if (config.getParentConfigFieldId() != null && !config.getParentConfigFieldId().equals(saveBo.getParentConfigFieldId())) {
                IsfdDatabaseModelConfigField previousField = fieldMapper.selectById(config.getParentConfigFieldId());
                if (previousField != null) {
                    previousField.setIsRelated(0);
                    fieldMapper.updateById(previousField);
                }
            }
        }
        // 保存关联
        parentField.setIsRelated(1);
        parentField.setFieldType(IsfdDatabaseModelFieldTypeEnum.MODEL.getValue());
        fieldMapper.updateById(parentField);
        saveBo.setParentConfigId(parentField.getModelId());
        saveBo.setParentConfigName(parentModel.getModelName());
        saveBo.setParentConfigFieldId(parentField.getId());
        saveBo.setParentConfigFieldName(parentField.getFieldName());
        saveBo.setVersionNumber(parentModel.getVersionNumber());
        saveBo.setNodeId(parentModel.getNodeId());
        saveBo.setNodeName(parentModel.getNodeName());
        saveBo.setModelName(parentField.getFieldChineseName());
        saveBo.setModelType(parentModel.getModelType());
    }

    private boolean isUpdatingConfig(IsfdDatabaseModelConfigSaveBo saveBo) {
        if (saveBo.getId() != null) {
            IsfdDatabaseModelConfig config = baseMapper.selectById(saveBo.getId());
            if (config == null) {
                throw new BaseException("未查询到数据库模型，id: " + saveBo.getId());
            }
            saveBo.setTableName(config.getTableName());
            return true;
        } // 其余情况为新增
        String tableName = UUID.randomUUID().toString();
        if (StringUtils.isBlank(tableName)) {
            throw new BaseException("没有表名");
        }
        saveBo.setTableName(tableName);
        saveBo.setIsPublished(0);
        return false;
    }

    /**
     * 新增 和 升级的时候维护根版本
     */
    private void saveOriginalVersionId(IsfdDatabaseModelConfig model, Long modelId, boolean isUpdate, Boolean isUpdatingConfig) {
        if (!isUpdate) {
            if (!isUpdatingConfig) {
                // 新增 根版本id 为自身id；升级 根版本id 为传入的id
                model.setOriginalVersionId(modelId);
                baseMapper.updateById(model);
            }
        }
    }

    private void saveFieldConfig(List<IsfdDatabaseModelConfigFieldBo> fieldBoList, Long modelId) {
        if (CollectionUtils.isEmpty(fieldBoList)) {
//            throw new BaseException("字段列表不能为空！");
        }
        List<Long> idList = fieldBoList.stream()
            .map(IsfdDatabaseModelConfigFieldBo::getId)
            .filter(Objects::nonNull).toList();
        // 删除不要的字段
        fieldMapper.delete(
            new LambdaUpdateWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, modelId)
                .notIn(!CollectionUtils.isEmpty(idList), IsfdDatabaseModelConfigField::getId, idList)
                .eq(IsfdDatabaseModelConfigField::getIsRelated, 0));
        // 保存新字段配置
        fieldBoList.forEach(fieldBo -> {
            fieldBo.setModelId(modelId);
            saveFieldConfig(fieldBo, null);
        });
        // 验证字段名不能有重复
        validateFieldNames(modelId);
    }

    private void saveFieldConfig(IsfdDatabaseModelConfigFieldBo fieldBo, Long parentId) {
        IsfdDatabaseModelConfigField fieldPo = MapstructUtils.convert(fieldBo, IsfdDatabaseModelConfigField.class);
        fieldPo.setParentFieldId(parentId);
        // 插入/更新数据
        fieldMapper.insertOrUpdate(fieldPo);
        // 如果不是对象, 结束
        if (!fieldPo.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.OBJECT.getValue()) &&
            !fieldPo.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.LIST.getValue())) {
            return;
        }
        if (CollectionUtils.isEmpty(fieldBo.getFieldList())) {
            throw new BaseException("字段类型为对象/列表，但没有子字段！字段：" + fieldPo.getFieldName());
        }
        for (IsfdDatabaseModelConfigFieldBo subFieldBo : fieldBo.getFieldList()) {
            subFieldBo.setModelId(fieldPo.getModelId());
            saveFieldConfig(subFieldBo, fieldPo.getId());
        }
    }

    private void validateFieldNames(Long modelId) {
        List<IsfdDatabaseModelConfigField> fieldList = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, modelId)
        );
        // 过滤特殊字段
        if (!Collections.disjoint(fieldList, IsfdDatabaseModelSpecialFieldNameEnum.allValues())) {
            throw new BaseException("不能使用特殊字段名称：" + IsfdDatabaseModelSpecialFieldNameEnum.allValues());
        }
        Set<String> uniqueCombinations = new HashSet<>();
        for (IsfdDatabaseModelConfigField field : fieldList) {
            String uniqueKey = field.getFieldName() + field.getParentFieldId();
            if (!uniqueCombinations.add(uniqueKey)) {
                throw new BaseException("同一模型下不能有相同字段名称！fieldName: " + field.getFieldName());
            }
        }
    }

    private void handleMongoOperations(IsfdDatabaseModelConfigSaveBo saveBo, boolean isUpdate) {
        try {
            String tableName = saveBo.getTableName();
            // 创建MongoDB集合
            if (!isUpdate) {
                mongoService.createCollection(tableName);
            }
            // 创建唯一索引
            List<String> uniqueFieldList = saveBo.getFieldList().stream()
                .filter(fieldBo -> fieldBo.getIsUnique() != null && fieldBo.getIsUnique() == 1
                    && !fieldBo.getFieldType().equals(IsfdDatabaseModelFieldTypeEnum.MODEL.getValue()))
                .map(IsfdDatabaseModelConfigFieldBo::getFieldName)
                .collect(Collectors.toList());
//            if (!CollectionUtils.isEmpty(uniqueFieldList)) {
//                mongoService.createCompoundIndex(tableName, uniqueFieldList, Boolean.TRUE);
//            }

        } catch (Exception e) {
            log.error("MongoDB操作失败：", e.getMessage());
            throw new BaseException("MongoDB操作失败：" + e.getMessage());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteConfig(Long id) {
        // 查询当前节点
        IsfdDatabaseModelConfig config = baseMapper.selectById(id);
        if (config == null) {
            throw new BaseException("未查询到数据库模型！id：" + id);
        }
        // 获取当前节点的所有子节点
        List<IsfdDatabaseModelConfig> childConfigs = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getParentConfigId, id)
        );
        // 递归删除子节点
        for (IsfdDatabaseModelConfig childConfig : childConfigs) {
            deleteConfig(childConfig.getId());  // 递归删除子节点
        }
        // 修改父模型关联字段
        if (config.getParentConfigId() != null && config.getParentConfigFieldId() != null) {
            IsfdDatabaseModelConfigField parentField = fieldMapper.selectById(config.getParentConfigFieldId());
            parentField.setIsRelated(0);
            fieldMapper.updateById(parentField);
        }
        // 删除当前节点相关字段数据
        int count = fieldMapper.delete(new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
            .eq(IsfdDatabaseModelConfigField::getModelId, id));
        // 删除关联关系
        if (config.getParentConfigId() == null) {
            // 改版后的关联关系只有一条，说明一个模型只能被 一个业务场景、一个要素库类型、一个业务系统使用
            List<IsfdBusinessDatabaseRefWithNameVo> allDataWithNames = isfdBusinessDatabaseRefMapper.getAllDataWithNames(null, null, Collections.singletonList(config.getId()), null);
            IsfdBusinessDatabaseRefWithNameVo isfdBusinessDatabaseRefWithNameVo = allDataWithNames.get(0);
            isfdBusinessDatabaseRefMapper.deleteById(isfdBusinessDatabaseRefWithNameVo.getId());
        }
        // 删除 MongoDB 数据表
        mongoService.dropCollection(config.getTableName());// 如果没有数据，删除数据表
        // 删除当前节点
        return baseMapper.deleteById(config) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteConfigByNodeId(Long nodeId) {
        List<IsfdDatabaseModelConfig> configList = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getParentConfigId, nodeId)
        );
        if (CollectionUtils.isEmpty(configList)) {
            return;
        }
        for (IsfdDatabaseModelConfig config : configList) {
            deleteConfig(config.getId());
        }
    }

    @Override
    public List<IsfdDatabaseModelTreeShowVo> queryModelTreeListByNodeId(Long nodeId, Integer rootModelOnly, IsfdBusinessDatabaseTypeEnum typeEnum) {
        LambdaQueryWrapper<IsfdDatabaseModelConfig> rootLqw = new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
            .eq(IsfdDatabaseModelConfig::getNodeId, nodeId)
            .isNull(IsfdDatabaseModelConfig::getParentConfigId);
        if (typeEnum != null) {
            rootLqw.eq(IsfdDatabaseModelConfig::getModelType, typeEnum.getValue());
        }
        List<IsfdDatabaseModelConfig> rootList = baseMapper.selectList(rootLqw);
        if (CollectionUtils.isEmpty(rootList)) {
            return null;
        }

        Map<Long, List<IsfdDatabaseModelConfig>> rootMap = rootList.stream()
            .collect(Collectors.groupingBy(
                config -> config.getOriginalVersionId() == null ? config.getId() : config.getOriginalVersionId()
            ));
        Map<Long, IsfdDatabaseModelConfigVo> latestConfigs = new HashMap<>();
        for (Map.Entry<Long, List<IsfdDatabaseModelConfig>> entry : rootMap.entrySet()) {
            Long sourceId = entry.getKey();
            List<IsfdDatabaseModelConfig> configList = entry.getValue();
            // 按照 previousVersionId 找到最新版本
            List<IsfdDatabaseModelConfigVo> configVoList = sortLatestConfigSimple(configList);
            IsfdDatabaseModelConfigVo latestConfig = configVoList.get(0);
            // 存储最新版本
            latestConfigs.put(sourceId, latestConfig);
        }
        LambdaQueryWrapper<IsfdDatabaseModelConfig> allSubNodeLqw = new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
            .eq(IsfdDatabaseModelConfig::getNodeId, nodeId)
            .isNotNull(IsfdDatabaseModelConfig::getParentConfigId);
        if (typeEnum != null) {
            allSubNodeLqw.eq(IsfdDatabaseModelConfig::getModelType, typeEnum.getValue());
        }
        List<IsfdDatabaseModelConfigVo> allSubNodes = baseMapper.selectVoList(allSubNodeLqw);
        Map<Long, List<IsfdDatabaseModelConfigVo>> allNodesMap = allSubNodes.stream()
            .collect(Collectors.groupingBy(IsfdDatabaseModelConfigVo::getParentConfigId));

        // 构建模型树
        return latestConfigs.values().stream()
            .map(config -> queryModelTree(config, allNodesMap, rootModelOnly))
            .collect(Collectors.toList());
    }

    private IsfdDatabaseModelConfig findLatestConfig(List<IsfdDatabaseModelConfig> configList) {
        // 用来追溯到最新版本
        IsfdDatabaseModelConfig latestConfig = null;
        // 假设 configList 中的模型是链式的，可以从任意一个 config 开始追溯
        configList.sort(Comparator.comparing(IsfdDatabaseModelConfig::getCreateTime));  // 按升序排列
        IsfdDatabaseModelConfig currentConfig = configList.get(0);
        // 追溯到最新版本
        while (true) {
            IsfdDatabaseModelConfig finalCurrentConfig = currentConfig;
            Optional<IsfdDatabaseModelConfig> nextConfigOpt = configList.stream()
                .filter(c -> c.getPreviousVersionId() != null && c.getPreviousVersionId().equals(finalCurrentConfig.getId()))
                .findFirst();
            if (nextConfigOpt.isPresent()) {
                currentConfig = nextConfigOpt.get();
            } else {
                break;
            }
        }
        return currentConfig;  // 返回最新版本
    }

    private List<IsfdDatabaseModelConfigVo> sortLatestConfigSimple(List<IsfdDatabaseModelConfig> configList) {
        if (CollectionUtils.isEmpty(configList)) {
            return null;
        }
        List<IsfdDatabaseModelConfigVo> result = configList.stream()
            .sorted(Comparator.comparing(IsfdDatabaseModelConfig::getCreateTime).reversed())
            .map(config -> {
                IsfdDatabaseModelConfigVo vo = MapstructUtils.convert(config, IsfdDatabaseModelConfigVo.class);
                vo.setIsLastestVersion(0);
                return vo;
            }).toList();
        result.get(0).setIsLastestVersion(1);
        return result;
    }


    private IsfdDatabaseModelTreeShowVo queryModelTree(IsfdDatabaseModelConfigVo root, Map<Long, List<IsfdDatabaseModelConfigVo>> nodeMap, Integer rootModelOnly) {
        if (root == null) {
            return null;
        }
        // 创建树节点
        IsfdDatabaseModelTreeShowVo treeNode = new IsfdDatabaseModelTreeShowVo();
        treeNode.setId(root.getId());
        treeNode.setNodeId(root.getNodeId());
        treeNode.setName(root.getModelName());
        treeNode.setType(root.getModelType());
        treeNode.setHasEligibleField(checkEligibleFields(root.getId()));
        treeNode.setVersionIdMap(getVersionIdMap(root.getId()));
        if (rootModelOnly == 1) {
            return treeNode;
        }
        // 获取当前节点的子节点列表
        List<IsfdDatabaseModelConfigVo> children = nodeMap.get(root.getId());
        if (CollectionUtils.isEmpty(children)) {
            return treeNode;
        }
        List<IsfdDatabaseModelTreeShowVo> childNodes = children.stream()
            .map(child -> queryModelTree(child, nodeMap, rootModelOnly))
            .toList();
        treeNode.setChildren(childNodes);
        return treeNode;
    }

    private boolean checkEligibleFields(Long modelId) {
        return fieldMapper.exists(new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
            .eq(IsfdDatabaseModelConfigField::getModelId, modelId)
            .eq(IsfdDatabaseModelConfigField::getFieldType, IsfdDatabaseModelFieldTypeEnum.MODEL.getValue())
            .eq(IsfdDatabaseModelConfigField::getIsRelated, 0));
    }

    @Override
    public List<String> getFieldTypes() {
        SysDictDataBo queryBo = new SysDictDataBo();
        queryBo.setDictType(CommonConstant.DATA_MODELING_FIELD_TYPES);
        List<SysDictDataVo> dataList = iSysDictDataService.selectDictDataList(queryBo);
        return dataList.stream()
            .sorted(Comparator.comparingInt(SysDictDataVo::getDictSort))
            .map(SysDictDataVo::getDictLabel).collect(Collectors.toList());
    }

    @Override
    public List<IsfdDatabaseModelConfigTableVo> getFieldTableList(Long modelId) {
        // 初始化结果列表
        List<IsfdDatabaseModelConfigTableVo> result = new ArrayList<>();

        // 获取主模型并处理
        getTableFieldsRecursively(modelId, result);

        // 确保主模型按最底层为第一位编号
        result.sort(Comparator.comparingInt(IsfdDatabaseModelConfigTableVo::getDepth));

        return result;
    }

    @Override
    public Map<String, Object> getTemplate(Long modelId) {
        IsfdDatabaseModelConfig config = Optional.ofNullable(baseMapper.selectById(modelId))
            .orElseThrow(() -> new BaseException("模型不存在，ID: " + modelId));

        Map<String, Object> result = new HashMap<>();
        getTemplateRecursively(config, result, null);
        return result;
    }

    public Resource downloadTemplate(Long modelId) {
        IsfdDatabaseModelConfig config = Optional.ofNullable(baseMapper.selectById(modelId))
            .orElseThrow(() -> new BaseException("模型不存在，ID: " + modelId));

        Map<String, Object> result = new HashMap<>();
        getTemplateRecursively(config, result, null);

        try {
            Map<String, Object> templateData = buildTemplateData(config);
            Path tempDir = createTemplateDirectory(templateData);
            Path zipPath = zipTemplateDirectory(tempDir);
            return buildDownloadResource(zipPath);
        } catch (Exception e) {
            log.error("生成模板失败：" + e.getMessage(), e);
            throw new RuntimeException("生成模板失败：" + e.getMessage());
        }
    }

    private Map<String, Object> buildTemplateData(IsfdDatabaseModelConfig config) {
        Map<String, Object> result = new HashMap<>();
        getTemplateRecursively(config, result, null);
        return result;
    }

    private Path createTemplateDirectory(Map<String, Object> templateData) throws IOException {
        Path tempDir = Files.createTempDirectory("data_template_");

        // 1. 写入 JSON 文件
        List<Map<String, Object>> dataList = Collections.singletonList(templateData);
        String json = JSONUtil.parse(dataList).toStringPretty();
        Files.write(tempDir.resolve("data.json"), json.getBytes(StandardCharsets.UTF_8));

        // 2. 创建空的 files 文件夹
        Files.createDirectories(tempDir.resolve("files"));

        // 3. 写入 readme.txt
        String readme = getReadmeContent();
        Files.write(tempDir.resolve("readme.txt"), readme.getBytes(StandardCharsets.UTF_8));

        return tempDir;
    }

    private String getReadmeContent() {
        return """
            # 数据模板使用说明

            本数据模板用于模型数据的结构化导入，支持以下两种上传方式：

            ---

            ## 上传方式一：完整上传 ZIP 包

            请将以下内容压缩为一个 ZIP 文件上传：

            data_template.zip
            ├── data.json    ← 必填，数据结构模板
            └── files/       ← 可选，放置引用的外部文件（如图片、PDF 等）

            说明：
            - data.json 是根据模型结构生成的数据。
            - files/ 文件夹内的文件可由 JSON 中某些字段引用。
            - json数据中引用文件的方式：{文件名}，示例："image" : "image_1.png"

            ---

            ## 上传方式二：仅上传 JSON 模板文件

            直接上传 data.json 文件，适用于不包含文件引用的场景。

            ---

            ## 字段说明

            - 根据数据模型确定：字段类型、是否能为空、是否唯一。

            """;
    }


    private Path zipTemplateDirectory(Path sourceDir) throws IOException {
        Path zipPath = Files.createTempFile("data_template_", ".zip");
        try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipPath))) {
            addToZip(sourceDir, sourceDir, zos);
        }
        return zipPath;
    }

    private void addToZip(Path rootDir, Path source, ZipOutputStream zos) throws IOException {
        Path relativePath = rootDir.relativize(source);
        String entryName = relativePath.toString().replace("\\", "/");

        if (Files.isDirectory(source)) {
            // 添加目录条目（即使为空）
            if (!entryName.endsWith("/")) {
                entryName += "/";
            }
            zos.putNextEntry(new ZipEntry(entryName));
            zos.closeEntry();

            // 遍历并递归添加子文件/目录
            try (Stream<Path> paths = Files.list(source)) {
                for (Path child : paths.toList()) {
                    addToZip(rootDir, child, zos);
                }
            }
        } else {
            // 添加文件
            zos.putNextEntry(new ZipEntry(entryName));
            Files.copy(source, zos);
            zos.closeEntry();
        }
    }

    private Resource buildDownloadResource(Path zipPath) throws IOException {
        byte[] zipBytes = Files.readAllBytes(zipPath);
        return new ByteArrayResource(zipBytes) {
            @Override
            public String getFilename() {
                return "data_template.zip";
            }
        };
    }


    private void getTemplateRecursively(IsfdDatabaseModelConfig config, Map<String, Object> result, Long parentFieldId) {
        if (parentFieldId != null) {
            throw new UnsupportedOperationException("复用 createFieldTree 模式下，不支持 parentFieldId 子集生成");
        }

        List<IsfdDatabaseModelConfigField> rootFields = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, config.getId())
                .isNull(IsfdDatabaseModelConfigField::getParentFieldId)
        );

        List<IsfdDatabaseModelConfigFieldVo> fieldTree = new ArrayList<>();
        for (IsfdDatabaseModelConfigField field : rootFields) {
            fieldTree.add(createFieldTree(field));
        }

        buildTemplateFromFieldTree(fieldTree, result);
    }

    private void buildTemplateFromFieldTree(List<IsfdDatabaseModelConfigFieldVo> fieldTree, Map<String, Object> result) {
        for (IsfdDatabaseModelConfigFieldVo field : fieldTree) {
            String fieldType = field.getFieldType();
            if (IsfdDatabaseModelFieldTypeEnum.MODEL.getValue().equals(fieldType) && field.getIsRelated() == 1) {
                // 处理子模型，递归整个模型结构
                IsfdDatabaseModelConfig childConfig = baseMapper.selectById(field.getRelatedModelId());
                if (childConfig == null) {
                    throw new BaseException("关联子模型不存在，ID: " + field.getRelatedModelId());
                }
                Map<String, Object> childMap = new HashMap<>();
                getTemplateRecursively(childConfig, childMap, null); // 原方法继续用
                result.put(field.getFieldName(), Collections.singletonList(childMap));

            } else if (IsfdDatabaseModelFieldTypeEnum.OBJECT.getValue().equals(fieldType)) {

                Map<String, Object> objectMap = new HashMap<>();
                buildTemplateFromFieldTree(field.getFieldList(), objectMap); // 递归构建
                result.put(field.getFieldName(), objectMap);

            } else if (IsfdDatabaseModelFieldTypeEnum.LIST.getValue().equals(fieldType)) {

                Map<String, Object> objectMap = new HashMap<>();
                buildTemplateFromFieldTree(field.getFieldList(), objectMap); // 递归构建
                result.put(field.getFieldName(), Collections.singletonList(objectMap));

            } else {
                result.put(field.getFieldName(), field.getDefaultValue() == null ? "" : field.getDefaultValue());
            }
        }
    }


    /**
     * 递归获取表字段并设置深度编号
     */
    private void getTableFieldsRecursively(Long modelId, List<IsfdDatabaseModelConfigTableVo> result) {
        // 获取当前模型配置
        IsfdDatabaseModelConfig config = Optional.ofNullable(baseMapper.selectById(modelId))
            .orElseThrow(() -> new BaseException("模型不存在，ID: " + modelId));
        if (StringUtils.isBlank(config.getTableName())) {
            throw new BaseException("模型表名为空，ID: " + modelId);
        }
        // 构建当前模型的表信息
        IsfdDatabaseModelConfigTableVo tableVo = new IsfdDatabaseModelConfigTableVo();
        tableVo.setId(config.getId());
        tableVo.setModelName(config.getModelName());
        tableVo.setTableName(config.getTableName());
        tableVo.setShowType(config.getShowType());
        if (config.getParentConfigId() != null) {
            String parentTableName = baseMapper.selectById(config.getParentConfigId()).getTableName();
            String parentFieldName = fieldMapper.selectById(config.getParentConfigFieldId()).getFieldName();
            tableVo.setParentTableName(parentTableName);
            tableVo.setParentFieldName(parentFieldName);
        }
        // 获取字段列表并转换为 VO
        List<IsfdDatabaseModelConfigField> fieldList = fieldMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
                .eq(IsfdDatabaseModelConfigField::getModelId, modelId)
                .isNull(IsfdDatabaseModelConfigField::getParentFieldId));
        List<IsfdDatabaseModelConfigFieldVo> fieldVoList = fieldList.stream()
            .map(this::createFieldTree).toList();
        // 处理字段，递归处理子模型
        for (IsfdDatabaseModelConfigFieldVo field : fieldVoList) {
            if (IsfdDatabaseModelFieldTypeEnum.MODEL.getValue().equals(field.getFieldType()) && field.getIsRelated() == 1) {
                // 关联子模型
                IsfdDatabaseModelConfig childConfig = baseMapper.selectOne(
                    new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                        .eq(IsfdDatabaseModelConfig::getParentConfigId, config.getId())
                        .eq(IsfdDatabaseModelConfig::getParentConfigFieldId, field.getId())
                );
                if (childConfig == null) {
                    throw new BaseException("关联子模型不存在，FieldID: " + field.getId() + "::模型name:" + config.getModelName());
                }
                // 递归获取子模型
                getTableFieldsRecursively(childConfig.getId(), result);
            }
        }
        tableVo.setFieldVoList(fieldVoList);
        // 设置深度编号
        tableVo.setDepth(result.size() + 1);
        // 将当前表添加到结果列表
        result.add(tableVo);
    }

    @Override
    public Map<String, IsfdDatabaseModelConfigFieldVo> getFieldMap(IsfdDatabaseModelConfigTableVo tableVo) {
        List<IsfdDatabaseModelConfigFieldVo> fieldVoList = tableVo.getFieldVoList();
        if (fieldVoList == null || fieldVoList.isEmpty()) {
            return Collections.emptyMap();
        }
        return fieldVoList.stream().collect(Collectors.toMap(
            IsfdDatabaseModelConfigFieldVo::getFieldName,
            field -> field
        ));
    }

    @Override
    public IsfdDatabaseModelConfigVo validateModelExistence(Long ModelId) {
        IsfdDatabaseModelConfigVo model = baseMapper.selectVoById(ModelId);
        if (model == null) {
            throw new BaseException("模型不存在！");
        }
        if (StringUtils.isBlank(model.getTableName())) {
            log.error("未配置导入位置！");
            throw new BaseException("未配置导入位置！");
        }
        return model;
    }


    @Override
    public List<IsfdDatabaseModelConfigVo> queryListAllVersionList(Long modelId) {
        IsfdDatabaseModelConfig currentConfig = baseMapper.selectById(modelId);
        if (currentConfig == null) {
            throw new BaseException("未找到模型，id：" + modelId);
        }
        Long originalVersionId = currentConfig.getOriginalVersionId() == null ? currentConfig.getId() : currentConfig.getOriginalVersionId();
        List<IsfdDatabaseModelConfig> relatedConfigs = baseMapper.selectList(
            new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
                .eq(IsfdDatabaseModelConfig::getOriginalVersionId, originalVersionId)
                .or()  // 使用 OR 连接
                .eq(IsfdDatabaseModelConfig::getId, originalVersionId)
        );
        relatedConfigs.sort(Comparator.comparing(IsfdDatabaseModelConfig::getCreateTime).reversed());
        return MapstructUtils.convert(relatedConfigs, IsfdDatabaseModelConfigVo.class);
    }


    @Override
    public Map<String, IsfdDatabaseModelConfigFieldVo> getFieldMap(Long modelId) {
        IsfdDatabaseModelConfigVo model = validateModelExistence(modelId);
        // 校验建模表中是否存在该表信息
        if (StringUtils.isBlank(model.getTableName())) {
            log.error("未配置导入位置！");
            throw new BaseException("未配置导入位置！");
        }
        List<IsfdDatabaseModelConfigFieldVo> fieldVoList = fieldMapper.selectVoList(new LambdaQueryWrapper<IsfdDatabaseModelConfigField>()
            .eq(IsfdDatabaseModelConfigField::getModelId, model.getId()));
        if (CollectionUtils.isEmpty(fieldVoList)) {
            log.error("未查询到相关数据表配置信息！");
            throw new BaseException("未查询到相关数据表配置信息！");
        }
        // 将 List 转换为 Map，以 fieldName 作为 key
        return fieldVoList.stream()
            .collect(Collectors.toMap(
                IsfdDatabaseModelConfigFieldVo::getFieldName, // key 提取器
                field -> field));
    }


    @Override
    public List<IsfdDatabaseModelConfigVo> getAllChildrenByParentConfigId(Long parentConfigId) {
        IsfdDatabaseModelConfigVo configVo = baseMapper.selectVoById(parentConfigId);
        if (configVo == null) {
            log.error("父模型不存在！parentConfigId is {}", parentConfigId);
            throw new BaseException("父模型不存在！");
        }
        List<IsfdDatabaseModelConfigVo> allChildren = new ArrayList<>();
        recursiveFindChildren(parentConfigId, allChildren);
        return allChildren;
    }

    private void recursiveFindChildren(Long parentId, List<IsfdDatabaseModelConfigVo> result) {
        List<IsfdDatabaseModelConfigVo> children = baseMapper.selectVoList(new LambdaQueryWrapper<IsfdDatabaseModelConfig>()
            .eq(IsfdDatabaseModelConfig::getParentConfigId, parentId));
        if (!CollectionUtils.isEmpty(children)) {
            result.addAll(children);
            for (IsfdDatabaseModelConfigVo child : children) {
                recursiveFindChildren(child.getId(), result);
            }
        }
    }

    @Override
    public IsfdDatabaseModelConfigVo queryByIdReturnSimpleVo(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public IsfdDatabaseModelConfig queryByIdReturnTopParent(Long modelId) {
        IsfdDatabaseModelConfig current = baseMapper.selectById(modelId);
        if (current == null) {
            return null;
        }

        while (current.getParentConfigId() != null) {
            IsfdDatabaseModelConfig parent = baseMapper.selectById(current.getParentConfigId());
            if (parent == null) {
                break; // 父节点不存在，直接返回当前节点
            }
            current = parent;
        }
        return current;
    }
}
